# -*- coding: utf-8 -*-
import network
import time
import socket

class NetServer(object):
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF) # create station interface
        self.wlan.active(True)       # activate the interface

    def connect(self, ssid, key, timeouts):
        self.wlan.connect(ssid, key)
        while timeouts:
            
            time.sleep(1)
            if self.wlan.isconnected():
                return True
            timeouts -= 1
        return False
    
    def boardcast(self, port, timeouts):
        #HOST = '<broadcast>'
        HOST = '255.255.255.255'
        PORT = port  
        ADDR = (HOST, PORT)
        udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udpCliSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        while timeouts>=0:  
            timeouts-=1
            data='i\'m a car from ip %s' %(self.wlan.ifconfig()[0])
            udpCliSock.sendto(data, ADDR)
            print("sending -> %s" %data)
            time.sleep(1)
        udpCliSock.close()

    def createServer(self, port):
        self.s = socket.socket()         # 创建 socket 对象
        self.s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        host = self.wlan.ifconfig()[0]
        self.s.bind((host, port))        # 绑定端口
        self.s.listen(5)                 # 最大链接个数 5
        

    def waitConnect(self, timeout):
        c,addr = self.s.accept()     # 建立客户端连接
        print('连接地址：', addr)
        c.send('欢迎访问 智能车一号，请输入指令')
        return c

    def readCmd(self, c, timeout):
        c.settimeout(timeout)
        try:
            b = c.recv(1)
            c.send(b)
            return b
        except OSError:
            return None
        


    


